package cn.krguang.gasalermjiangshan;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private String TAG = "test123";
    private static final String YANG_QI_LEVEL = "yangQiLevel";
    private static final String XIAO_QI_LEVEL = "xiaoQiLevel";
    private static final String YA_QI_LEVEL = "yaQiLevel";
    private static final String DAN_QI_LEVEL = "danQiLevel";
    private static final String FU_YA_LEVEL = "fuYaLevel";
    private static final String YA_SUO_LEVEL = "yaSuoKongQiLevel";
    private static final String ER_YANG_HUA_TAN_LEVEL = "erYangHuaTanLevel";

    private static final String YANG_QI_VALUE = "yangQiReal";
    private static final String XIAO_QI_VALUE = "xiaoQiReal";
    private static final String YA_QI_VALUE = "yaQiReal";
    private static final String DAN_QI_VALUE = "danQiReal";
    private static final String FU_YA_VALUE = "fuYaReal";
    private static final String YA_SUO_VALUE = "yaSuoKongQiReal";
    private static final String ER_YANG_HUA_TAN_VALUE = "erYangHuaTanReal";

    private static final String TOPIC1 = "device/gas/jiangshanzhongyiyuan/866262046474010";
    private static final String TOPIC2 = "device/gas/jiangshanzhongyiyuan/866262045659082";
    private static final String TOPIC3 = "device/gas/jiangshanzhongyiyuan/866262046474044";

    private TextView tv_yangQiGuanValue1;
    private TextView tv_yangQiGuanValue2;

    //0:正常   1:超压  2:欠压
    private Button bt_yaSuo1ZhengChang;
    private Button bt_yaSuo1QianYa;
    private Button bt_yaSuo1ChaoYa;

    private Button bt_yaSuo2ZhengChang;
    private Button bt_yaSuo2QianYa;
    private Button bt_yaSuo2ChaoYa;

  //  private Button bt_fuYaZhengChang;
 //   private Button bt_fuYaQianYa;
  //  private Button bt_fuYaChaoYa;

    private Button bt_yangQiZhengChang;
    private Button bt_yangQiQianYa;
    private Button bt_yangQiChaoYa;

    private Button zhiShi;

    private int yeYangGuanValue1;
    private int yeYangGuanValue2;

    private int yaSuoKongQiLevel1;
    private int yaSuoKongQiLevel2;
    private int fuYaLevel;

    private int yangQiLevel;

    private int count=1000;

    private int yaSuo1temp;
    private int yaSuo2temp;
    private int yangQitemp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        checkPermission();

        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {      // UI thread
                    public void run() {
                        try {
                            count++;
                            if (count>1000){
                                count = 1000;
                            }

                            if (count<60){
                                zhiShi.setBackgroundResource(R.drawable.qitizhengchang);
                            }else {
                                zhiShi.setBackgroundResource(R.drawable.init_ing);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        },0,1000);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MyMqttClient.sharedCenter().setConnect();
        MyMqttClient.sharedCenter().setOnServerReadStringCallback(new MyMqttClient.OnServerReadStringCallback() {
            @Override
            public void callback(String Topic, MqttMessage Msg) {
                getAndProcessData(Topic, Msg);
            }
        });
    }

    private void getAndProcessData(String topic, MqttMessage message){
        count = 0;
        switch (topic) {
            case TOPIC1:
                try {
                    JSONObject jsonObject = new JSONObject(message.toString());

                    String yangQiValueTemp = jsonObject.has(YANG_QI_VALUE) ? jsonObject.getString(YANG_QI_VALUE) : "";
                    if (!yangQiValueTemp.equals("")) {
                        try {
                            yeYangGuanValue1 = Integer.parseInt(yangQiValueTemp);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    String yaQiValueTemp = jsonObject.has(YA_QI_VALUE) ? jsonObject.getString(YA_QI_VALUE) : "";
                    if (!yaQiValueTemp.equals("")) {
                        try {
                            yeYangGuanValue2 = Integer.parseInt(yaQiValueTemp);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case TOPIC2:
                try {
                    JSONObject jsonObject = new JSONObject(message.toString());

                    String yangQiLevelTemp = jsonObject.has(YANG_QI_LEVEL) ? jsonObject.getString(YANG_QI_LEVEL) : "";
                    if (!yangQiLevelTemp.equals("")) {
                        try {
                            yaSuoKongQiLevel1 = Integer.parseInt(yangQiLevelTemp);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    String yaQiLevelTemp = jsonObject.has(YA_QI_LEVEL) ? jsonObject.getString(YA_QI_LEVEL) : "";
                    if (!yaQiLevelTemp.equals("")) {
                        try {
                            yaSuoKongQiLevel2 = Integer.parseInt(yaQiLevelTemp);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    String xiaoQiLevelTemp = jsonObject.has(XIAO_QI_LEVEL) ? jsonObject.getString(XIAO_QI_LEVEL) : "";
                    if (!xiaoQiLevelTemp.equals("")) {
                        try {
                            fuYaLevel = Integer.parseInt(xiaoQiLevelTemp);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case TOPIC3:
                try {
                    JSONObject jsonObject = new JSONObject(message.toString());

                    String yangQiLevelTemp = jsonObject.has(YANG_QI_LEVEL) ? jsonObject.getString(YANG_QI_LEVEL) : "";
                    if (!yangQiLevelTemp.equals("")) {
                        try {
                            yangQiLevel = Integer.parseInt(yangQiLevelTemp);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:break;
        }
        tv_yangQiGuanValue1.setText(yeYangGuanValue1+"KPa");
        tv_yangQiGuanValue2.setText(yeYangGuanValue2+"KPa");

        switch (yaSuoKongQiLevel1){
            case 0:
                bt_yaSuo1ZhengChang.setBackgroundResource(R.drawable.qitizhengchang);
                bt_yaSuo1QianYa.setBackgroundResource(R.drawable.init_ing);
                bt_yaSuo1ChaoYa.setBackgroundResource(R.drawable.init_ing);
                break;
            case 1:
                bt_yaSuo1ZhengChang.setBackgroundResource(R.drawable.init_ing);
                bt_yaSuo1QianYa.setBackgroundResource(R.drawable.qitiqianya);
                bt_yaSuo1ChaoYa.setBackgroundResource(R.drawable.init_ing);
                break;
            case 2:
                bt_yaSuo1ZhengChang.setBackgroundResource(R.drawable.init_ing);
                bt_yaSuo1QianYa.setBackgroundResource(R.drawable.init_ing);
                bt_yaSuo1ChaoYa.setBackgroundResource(R.drawable.qitichaoya);
                break;
            default:break;
        }

        switch (yaSuoKongQiLevel2){
            case 0:
                bt_yaSuo2ZhengChang.setBackgroundResource(R.drawable.qitizhengchang);
                bt_yaSuo2QianYa.setBackgroundResource(R.drawable.init_ing);
                bt_yaSuo2ChaoYa.setBackgroundResource(R.drawable.init_ing);
                break;
            case 1:
                bt_yaSuo2ZhengChang.setBackgroundResource(R.drawable.init_ing);
                bt_yaSuo2QianYa.setBackgroundResource(R.drawable.qitiqianya);
                bt_yaSuo2ChaoYa.setBackgroundResource(R.drawable.init_ing);
                break;
            case 2:
                bt_yaSuo2ZhengChang.setBackgroundResource(R.drawable.init_ing);
                bt_yaSuo2QianYa.setBackgroundResource(R.drawable.init_ing);
                bt_yaSuo2ChaoYa.setBackgroundResource(R.drawable.qitichaoya);
                break;
            default:break;
        }

//        switch (fuYaLevel){
//            case 0:
//                bt_fuYaZhengChang.setBackgroundResource(R.drawable.qitizhengchang);
//                bt_fuYaQianYa.setBackgroundResource(R.drawable.init_ing);
//                bt_fuYaChaoYa.setBackgroundResource(R.drawable.init_ing);
//                break;
//            case 1:
//                bt_fuYaZhengChang.setBackgroundResource(R.drawable.init_ing);
//                bt_fuYaQianYa.setBackgroundResource(R.drawable.qitiqianya);
//                bt_fuYaChaoYa.setBackgroundResource(R.drawable.init_ing);
//                break;
//            case 2:
//                bt_fuYaZhengChang.setBackgroundResource(R.drawable.init_ing);
//                bt_fuYaQianYa.setBackgroundResource(R.drawable.init_ing);
//                bt_fuYaChaoYa.setBackgroundResource(R.drawable.qitichaoya);
//                break;
//            default:break;
//        }

        switch (yangQiLevel){
            case 0:
                bt_yangQiZhengChang.setBackgroundResource(R.drawable.qitizhengchang);
                bt_yangQiQianYa.setBackgroundResource(R.drawable.init_ing);
                bt_yangQiChaoYa.setBackgroundResource(R.drawable.init_ing);
                break;
            case 1:
                bt_yangQiZhengChang.setBackgroundResource(R.drawable.init_ing);
                bt_yangQiQianYa.setBackgroundResource(R.drawable.qitiqianya);
                bt_yangQiChaoYa.setBackgroundResource(R.drawable.init_ing);
                break;
            case 2:
                bt_yangQiZhengChang.setBackgroundResource(R.drawable.init_ing);
                bt_yangQiQianYa.setBackgroundResource(R.drawable.init_ing);
                bt_yangQiChaoYa.setBackgroundResource(R.drawable.qitichaoya);
                break;
            default:break;
        }

        if (yaSuo1temp != yaSuoKongQiLevel1){
            yaSuo1temp = yaSuoKongQiLevel1;
            switch (yaSuo1temp){
                case 0:
                    sendMessage(1,"压缩空气1恢复正常");
                    break;
                case 1:
                    sendMessage(1,"压缩空气1欠压");
                    break;
                case 2:
                    sendMessage(1,"压缩空气1超压");
                    break;
            }
        }

        if (yaSuo2temp != yaSuoKongQiLevel2){
            yaSuo2temp = yaSuoKongQiLevel2;
            switch (yaSuo2temp){
                case 0:
                    sendMessage(2,"压缩空气2恢复正常");
                    break;
                case 1:
                    sendMessage(2,"压缩空气2欠压");
                    break;
                case 2:
                    sendMessage(2,"压缩空气2超压");
                    break;
            }
        }

        if (yangQitemp != yangQiLevel){
            yangQitemp = yangQiLevel;
            switch (yangQitemp){
                case 0:
                    sendMessage(3,"氧气恢复正常");
                    break;
                case 1:
                    sendMessage(3,"氧气欠压");
                    break;
                case 2:
                    sendMessage(3,"氧气超压");
                    break;
            }
        }

    }


    private void initView() {
        tv_yangQiGuanValue1 = findViewById(R.id.yang_qi_guan_value1);
        tv_yangQiGuanValue2 = findViewById(R.id.yang_qi_guan_value2);

        bt_yaSuo1ZhengChang = findViewById(R.id.ya_suo_kong_qi_1_zhengchang);
        bt_yaSuo1QianYa = findViewById(R.id.ya_suo_kong_qi_1_qianya);
        bt_yaSuo1ChaoYa = findViewById(R.id.ya_suo_kong_qi_1_chaoya);

        bt_yaSuo2ZhengChang = findViewById(R.id.ya_suo_kong_qi_2_zhengchang);
        bt_yaSuo2QianYa = findViewById(R.id.ya_suo_kong_qi_2_qianya);
        bt_yaSuo2ChaoYa = findViewById(R.id.ya_suo_kong_qi_2_chaoya);

//        bt_fuYaZhengChang = findViewById(R.id.fu_ya_zhengchang_id);
//        bt_fuYaQianYa = findViewById(R.id.fu_ya_qianya_id);
//        bt_fuYaChaoYa = findViewById(R.id.fu_ya_chaoya_id);

        bt_yangQiZhengChang = findViewById(R.id.yang_qi_zhengchang_id);
        bt_yangQiQianYa = findViewById(R.id.yang_qi_qianya_id);
        bt_yangQiChaoYa = findViewById(R.id.yang_qi_chaoya_id);

        zhiShi = findViewById(R.id.zhi_shi);
    }

    public void checkPermission()
    {
        int targetSdkVersion = 0;
        String[] PermissionString={Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA};
        try {
            final PackageInfo info = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
            targetSdkVersion = info.applicationInfo.targetSdkVersion;//获取应用的Target版本
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
//            Log.e("err", "检查权限_err0");
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //Build.VERSION.SDK_INT是获取当前手机版本 Build.VERSION_CODES.M为6.0系统
            //如果系统>=6.0
            if (targetSdkVersion >= Build.VERSION_CODES.M) {
                //第 1 步: 检查是否有相应的权限
                boolean isAllGranted = checkPermissionAllGranted(PermissionString);
                if (isAllGranted) {
                    //Log.e("err","所有权限已经授权！");
                    return;
                }
                // 一次请求多个权限, 如果其他有权限是已经授予的将会自动忽略掉
                ActivityCompat.requestPermissions(this,
                        PermissionString, 1);
            }
        }
    }

    /**
     * 检查是否拥有指定的所有权限
     */
    private boolean checkPermissionAllGranted(String[] permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                // 只要有一个权限没有被授予, 则直接返回 false
                //Log.e("err","权限"+permission+"没有授权");
                return false;
            }
        }
        return true;
    }


    private void sendMessage(int id,String Text){

        NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        String channelId = "app1";
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,"app1",NotificationManager.IMPORTANCE_DEFAULT);
            manager.createNotificationChannel(channel);
        }

        Intent intent = new Intent(MainActivity.this,MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(MainActivity.this,0,intent,0);

        Notification notification = new NotificationCompat.Builder(MainActivity.this, channelId)
                //    .setContentTitle("")
                .setContentText(Text)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                .setContentIntent(pi)
                .setAutoCancel(true)
                .build();
        manager.notify(id,notification);
    }
}